using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 表单提交仓储实现
    /// </summary>
    public class FormSubmissionRepository : Repository<FormSubmission>, IFormSubmissionRepository
    {
        public FormSubmissionRepository(LowCodeDbContext context) : base(context)
        {
        }

        public async Task<List<FormSubmission>> GetByFormIdAsync(long formId)
        {
            return await _context.FormSubmissions
                .Where(fs => fs.FormId == formId && fs.Status != 0)
                .OrderByDescending(fs => fs.SubmitTime)
                .ToListAsync();
        }

        public async Task<IEnumerable<FormSubmission>> GetByUserAsync(string userIdentifier)
        {
            return await _context.FormSubmissions
                .Where(fs => fs.SubmitterId.ToString() == userIdentifier && fs.Status != 0)
                .OrderByDescending(fs => fs.SubmitTime)
                .ToListAsync();
        }

        public async Task<(IEnumerable<FormSubmission> Items, int TotalCount)> GetPagedAsync(
            int pageIndex, 
            int pageSize, 
            long? formId = null, 
            string? status = null, 
            DateTime? startDate = null, 
            DateTime? endDate = null)
        {
            var query = _context.FormSubmissions.Where(fs => fs.Status != 0);

            if (formId.HasValue)
                query = query.Where(fs => fs.FormId == formId.Value);

            if (!string.IsNullOrEmpty(status))
                query = query.Where(fs => fs.Status.ToString() == status);

            if (startDate.HasValue)
                query = query.Where(fs => fs.SubmitTime >= startDate.Value);

            if (endDate.HasValue)
                query = query.Where(fs => fs.SubmitTime <= endDate.Value);

            var totalCount = await query.CountAsync();
            var items = await query
                .OrderByDescending(fs => fs.SubmitTime)
                .Skip(pageIndex * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (items, totalCount);
        }

        public async Task<Dictionary<string, int>> GetSubmissionStatisticsAsync(long formId)
        {
            var stats = await _context.FormSubmissions
                .Where(fs => fs.FormId == formId && fs.Status != 0)
                .GroupBy(fs => fs.Status)
                .Select(g => new { Status = g.Key.ToString(), Count = g.Count() })
                .ToDictionaryAsync(x => x.Status, x => x.Count);

            return stats;
        }

        public async Task<bool> ExportAsync(long formId, string filePath)
        {
            try
            {
                var submissions = await GetByFormIdAsync(formId);
                // 简单导出逻辑 - 实际项目中可使用CSV库
                await System.IO.File.WriteAllTextAsync(filePath, 
                    string.Join("\n", submissions.Select(s => $"{s.Id},{s.SubmitTime},{s.Data}")));
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> BatchDeleteAsync(IEnumerable<long> ids)
        {
            try
            {
                var submissions = await _context.FormSubmissions
                    .Where(fs => ids.Contains(fs.Id))
                    .ToListAsync();

                foreach (var submission in submissions)
                {
                    submission.Status = 2; // 设置为已忽略状态
                    submission.ProcessedAt = DateTime.UtcNow;
                }

                await SaveChangesAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> UpdateStatusAsync(long id, int status)
        {
            try
            {
                var submission = await GetByIdAsync(id);
                if (submission != null)
                {
                    submission.Status = (byte)status;
                    submission.ProcessedAt = DateTime.UtcNow;
                    await SaveChangesAsync();
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        public async Task<FormSubmission?> GetByReferenceNumberAsync(string referenceNumber)
        {
            // ReferenceNumber 属性不存在，使用 Id 进行查找
            if (long.TryParse(referenceNumber, out var id))
            {
                return await _context.FormSubmissions
                    .FirstOrDefaultAsync(fs => fs.Id == id && fs.Status != 0);
            }
            return null;
        }

        public async Task<int> GetTotalSubmissionsAsync(long formId)
        {
            return await _context.FormSubmissions
                .CountAsync(fs => fs.FormId == formId && fs.Status != 0);
        }

        public async Task<List<FormSubmission>> GetRecentSubmissionsAsync(int days = 7)
        {
            var startDate = DateTime.UtcNow.AddDays(-days);
            return await _context.FormSubmissions
                .Where(fs => fs.SubmitTime >= startDate && fs.Status != 0)
                .OrderByDescending(fs => fs.SubmitTime)
                .ToListAsync();
        }

        public async Task<List<FormSubmission>> GetByStatusAsync(string status)
        {
            if (byte.TryParse(status, out var statusByte))
            {
                return await _context.FormSubmissions
                    .Where(fs => fs.Status == statusByte && fs.Status != 0)
                    .OrderByDescending(fs => fs.SubmitTime)
                    .ToListAsync();
            }
            return new List<FormSubmission>();
        }

        public async Task<List<FormSubmission>> GetBySubmitterAsync(string submitterEmail)
        {
            // 根据 SubmitterId 查找，因为没有 SubmitterEmail 属性
            if (long.TryParse(submitterEmail, out var submitterId))
            {
                return await _context.FormSubmissions
                    .Where(fs => fs.SubmitterId == submitterId && fs.Status != 0)
                    .OrderByDescending(fs => fs.SubmitTime)
                    .ToListAsync();
            }
            return new List<FormSubmission>();
        }

        public async Task<bool> BatchUpdateStatusAsync(List<long> submissionIds, string status)
        {
            try
            {
                if (byte.TryParse(status, out var statusByte))
                {
                    var submissions = await _context.FormSubmissions
                        .Where(fs => submissionIds.Contains(fs.Id) && fs.Status != 0)
                        .ToListAsync();

                    foreach (var submission in submissions)
                    {
                        submission.Status = statusByte;
                        submission.ProcessedAt = DateTime.UtcNow;
                    }

                    await _context.SaveChangesAsync();
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
    }
}
